package com.bw.lib_base.base

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<VDB:ViewDataBinding,VM:BaseViewModel>:Fragment() {
    //获取当前类的泛型参数列表
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }
    private var isLoaded = false
    private var isVisibleToUser = false
    protected val vm:VM by lazy {
        //读取第二个参数
        val clazz = type[1] as Class<VM>
        //根据传入的VideModel获取对应的VideModel对象
        ViewModelProvider(requireActivity())[clazz]
    }

    private var _binding: VDB? = null
    protected val binding get() = _binding!!

    fun onError(t:Throwable){
        Log.i("===",t.message.toString())
        t.printStackTrace()
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val clazz = type[0] as Class<VDB>
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        _binding = method.invoke(null,layoutInflater) as VDB

        //将viewModel作为观察者注册给activity
        this.lifecycle.addObserver(vm)

        return binding.root
    }

    override fun onResume() {
        super.onResume()
        //模板方法
        //1.建立UI
        setupUI()
        //2.获取数据
        fetchData()
        //3.观察接受数据
        observeData()
        //4.处理事件
        handleEvent()
        // Fragment可见且未加载过
        if (!isLoaded && isVisibleToUser) {
            lazyLoad()
            isLoaded = true
        }
    }

    abstract fun setupUI()
    abstract fun fetchData()
    abstract fun observeData()
    abstract fun handleEvent()

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
    abstract val mLayoutResId: Int

    //新增页面懒加载缓存
    override fun onPause() {
        super.onPause()
        // 不可见时释放资源
        if (isLoaded) {
            onInvisible()
            isLoaded = false
        }
    }
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        this.isVisibleToUser = isVisibleToUser
        // 兼容旧版ViewPager
        if (isVisibleToUser && !isLoaded && isResumed) {
            lazyLoad()
            isLoaded = true
        }
    }

    abstract fun lazyLoad()
    open fun onInvisible() {}
}